package com.example.wacoffee_manage.controller;


import cn.hutool.json.JSONUtil;
import com.example.wacoffee_manage.Service.couponService;
import com.example.wacoffee_manage.pojo.coupon;
import com.example.wacoffee_manage.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/coupons")
public class couponController {

    @Autowired
    private couponService couponService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @GetMapping
    public Result getAll() {
        List<coupon>  coupons =couponService.getAll();
        return Result.success(coupons);
    }

    @PostMapping
    public Result add(@RequestBody coupon coupon){
        if(coupon.getValue()<=0)throw new RuntimeException("优惠卷价值不能小于等于0");
        if(coupon.getMinAmount()<=0)throw new RuntimeException("优惠卷最小金额不能小于等于0");
        if(coupon.getMinAmount()<=coupon.getValue())throw new RuntimeException("优惠卷价值不能大于等于最小金额");
        couponService.add(coupon);
        stringRedisTemplate.opsForValue().set("coupons:stock:"+coupon.getId(), coupon.getStock().toString());
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        couponService.delete(id);
        stringRedisTemplate.delete("coupons:stock:"+id);
        return Result.success();
    }

    @PutMapping("/{id}")
    public Result update(@PathVariable Integer id,@RequestBody coupon coupon){
        if(coupon.getValue()<=0)throw new RuntimeException("优惠卷价值不能小于等于0");
        if(coupon.getMinAmount()<=0)throw new RuntimeException("优惠卷最小金额不能小于等于0");
        if(coupon.getMinAmount()<=coupon.getValue())throw new RuntimeException("优惠卷价值不能大于等于最小金额");
        coupon.setId(id);
        couponService.update(coupon);
        stringRedisTemplate.opsForValue().set("coupons:stock:"+id, couponService.getById(id).getStock().toString());
        return Result.success();
    }

    @PutMapping("/{id}/{status}")
    public Result updateStatus(@PathVariable Integer id,@PathVariable Integer status){
        couponService.updateStatus(id,status);
        return Result.success();
    }
}
